/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.inspur.edp.lcm.metadata.common.configuration;

import com.inspur.edp.lcm.metadata.common.FileServiceImp;
import io.iec.edp.caf.common.environment.EnvironmentUtil;
import java.nio.file.Paths;

public class MenuConfigLoader {

    private static String menuFileName = "web/platform/dev/main/web/webide/ide.module.ngfactory";
    private static String menuExtendFileName = "config/platform/common/lcm_menuextend.conf";
    private static FileServiceImp fileService = new FileServiceImp();

    public MenuConfigLoader() {
    }

    static String menuConfiguration;
    static String menuExtendConfiguration;

    public String getMenuExtendConfiguration(Boolean status) {
        String fileName = Paths.get(EnvironmentUtil.getServerRTPath()).resolve(menuExtendFileName).toString();
        String contents = null;

        contents = fileService.fileRead(fileName);

        String flag = status ? "on:" : "off:";
        menuExtendConfiguration = contents.substring(contents.indexOf(flag) + flag.length(), contents.indexOf("\n", contents.indexOf(flag)) - 1);
        return menuExtendConfiguration;
    }

    public void setMenuConfiguration(String configuration) {
        String fileName = Paths.get(EnvironmentUtil.getBasePath()).resolve(menuFileName).toString();
        String contents = null;

        contents = fileService.fileRead(fileName);

        String extendOnMenu = getMenuExtendConfiguration(true);
        String extendOffMenu = getMenuExtendConfiguration(false);
        String oldString = contents.contains(extendOffMenu) ? extendOffMenu : extendOnMenu;
        String contentsUpdated = contents.replace(oldString, configuration);
        fileService.fileUpdate(fileName, contentsUpdated, false);
    }
}
